// app.js
import { join } from "path";
const { existsSync, mkdirSync, readdirSync, unlinkSync, rmdirSync, rmSync, statSync, lstatSync } = require('fs');
/**
 * Load all modules in a directory and return an array of instances
 * @param dir The directory to load modules from
 */
function loadModules(dir) {
    const instances = [];
    for (const file of readdirSync(dir)) {
        const filepath = join(dir, file);
        const module = require(filepath);
        if (module.default && typeof module.default === "function") {
            instances.push(new module.default());
        }
    }
    return instances;
}

/**
 * Check if a path points to a directory
 * @param path The path to check
 */
function isDirectory(path) {
    try {
        return statSync(path).isDirectory();
    } catch (error) {
        return false;
    }
}
function dirChekck(directoryPath) {
    if (!existsSync(directoryPath)) {
        mkdirSync(directoryPath, { recursive: true });
        console.log(`创建目录：${directoryPath}`);
    } else {
        console.log(`目录已存在：${directoryPath}`);
        const files = readdirSync(directoryPath);

        files.forEach((file) => {
            const filePath = `${directoryPath}/${file}`;

            if (existsSync(filePath)) {
                if (existsSync(filePath)) {
                    if (lstatSync(filePath).isDirectory()) {
                        // 删除子目录
                        rmdirSync(filePath, { recursive: true });
                        console.log(`已删除子目录：${filePath}`);
                    } else {
                        // 删除文件
                        unlinkSync(filePath);
                        console.log(`已删除文件：${filePath}`);
                    }
                }
            }
        });

        // 删除空目录
        // rmSync(directoryPath, { recursive: true });
        console.log(`已删除目录：${directoryPath}`);
    }
}
// Load all modules in the /src/package directory
// const instances = loadModules(join(__dirname, "src/package"));
export { loadModules, dirChekck };